/**
 * User: 吕维宇
 * Email: root@newmoon.cn
 * Date: 2019/5/17
 * 生成bmp格式buffer，方便进一步处理
 * 修改为原点坐标为左上
 */

class Bmp{
    constructor(width,height,data) {
        //修改原点坐标为左上
        const temp_data=data.toString('hex');
        data='';
        for(let i=height-1;i>=0;i--){
            data+=temp_data.substr(i*width*6,width*6);
        }
        data=new Buffer.from(data,'hex');

        //修正data必须为4的倍数
        let add_byte='';
        if(width*3%4 !== 0){
            for(let i=0;i<4-width*3%4;i++){
                add_byte+='00';
            }

            const temp_data2=data.toString('hex');
            data='';
            for(let i=0;i<height;i++){
                data+=temp_data2.substr(i*width*6,width*6)+add_byte;
            }
            data=new Buffer.from(data,'hex');
        }

        //位图文件头(bitmap-file header)
        const bfType=new Buffer.from('424D','hex');
        const bfSize=new Buffer.from(this.reversed_order(width*height*3+54+add_byte.length*height/2),'hex');
        const bfReserved=new Buffer.from('00000000','hex');
        const bfOffBits=new Buffer.from('36000000','hex');
        const bf=Buffer.concat([bfType,bfSize,bfReserved,bfOffBits]);

        //位图信息头(bitmap-information header)
        const biSize=new Buffer.from('28000000','hex');
        const biWidth=new Buffer.from(this.reversed_order(width),'hex');
        const biHeight=new Buffer.from(this.reversed_order(height),'hex');
        const biPlanes=new Buffer.from('0100','hex');
        const biBitCount=new Buffer.from('1800','hex');
        const biCompression=new Buffer.from('00000000','hex');
        const biSizeImage=new Buffer.from(this.reversed_order(width*height*3),'hex');
        const biXPelsPerMeter=new Buffer.from('6d0b0000','hex');
        const biYPelsPerMeter=new Buffer.from('6d0b0000','hex');
        const biClrUsed=new Buffer.from('00000000','hex');
        const biClrImportant=new Buffer.from('00000000','hex');
        const bi=Buffer.concat([biSize,biWidth,biHeight,biPlanes,biBitCount,biCompression,biSizeImage,biXPelsPerMeter,biYPelsPerMeter,biClrUsed,biClrImportant]);


        Bmp.pic=Buffer.concat([bf,bi,data]);
    }
    out(){
        return Bmp.pic;
    }
    reversed_order(num){
        const str=num.toString(16);
        const hex='00000000'.substr(0,8-str.length)+str; //补全变量字符数为8
        let back='';
        let i=0;
        while(hex.length>=2*i){
            back+=hex.substr(hex.length-2*i,2);
            i++;
        }
        return back;
    }
}

module.exports = Bmp;